package com.zhengbo.simplerpc.test;

import com.zhengbo.simplerpc.common.IMessageHandler;
import com.zhengbo.simplerpc.common.MessageOutput;
import com.zhengbo.simplerpc.server.RpcServer;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhengbo on 2019/8/23.
 */
@Slf4j
class ExpRequestHandler implements IMessageHandler<ExpRequest> {

    @Override
    public void handler(ChannelHandlerContext ctx, String requestId, ExpRequest message) {

        log.info("ExpRequestHandler handler:{},{},{}", ctx, requestId, message);

        int base = message.getBase();
        int exp = message.getExp();
        long start = System.nanoTime();

        long res = 1;

        for (int i = 0; i < exp; i++) {
            res *= base;
        }

        long cost = System.nanoTime() - start;

        ctx.writeAndFlush(new MessageOutput(requestId, "exp_res", new ExpResponse(res, cost)));
    }
}

@Slf4j
public class DemoService {


    public static void main(String[] args) {

        RpcServer rpcServer = new RpcServer("localhost", 9001, 2, 16);

        rpcServer.addServer("expCalc", ExpRequest.class, new ExpRequestHandler());

        rpcServer.startServer();
    }
}
